package com.service.thirddatacenter.hpool.client.decoder;

import com.alibaba.fastjson.JSON;
import com.service.core.exception.CommonException;
import feign.FeignException;
import feign.Response;
import feign.Util;
import feign.codec.DecodeException;
import feign.codec.Decoder;
import jodd.net.HttpStatus;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.lang.reflect.Type;

@Slf4j
public class JsonDecoder implements Decoder {
    @Override
    public Object decode(Response response, Type type) throws IOException, DecodeException, FeignException {
        if (response.status() == HttpStatus.ok().status()) {
            if (response.body() == null) {
                log.error("接口异常，无响应内容:status={},body={}", response.status(), response.body());
                throw new CommonException("接口异常");
            }
            String body = Util.toString(response.body().asReader(Util.UTF_8));
            log.debug("接口响应体：type={},body={}", type, body);
            return JSON.parseObject(body, type);
        } else {
            log.error("接口异常:status={},body={}", response.status(), response.body());
            throw new CommonException("接口异常");
        }
    }
}
